package com.fengye.proxy.dynamic.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * JDK 动态代理的写法
 *
 * @author gaohaiqing
 * @since 2023/12/12
 */
public class JDKDynamicProxyExample {
    public static void main(String[] args) {
        // 创建被代理的对象
        RealSubject realSubject = new RealSubject();

        // 创建 InvocationHandler 实例
        InvocationHandler handler = new MyInvocationHandler(realSubject);

        // 使用 Proxy 类的静态方法创建代理对象
        Subject proxySubject = (Subject) Proxy.newProxyInstance(
                RealSubject.class.getClassLoader(),
                RealSubject.class.getInterfaces(),
                handler
        );

        // 调用代理对象的方法
        proxySubject.request();
    }
}

interface Subject {
    void request();
}

class RealSubject implements Subject {
    public void request() {
        System.out.println("RealSubject: Handling request.");
    }
}

class MyInvocationHandler implements InvocationHandler {
    private final RealSubject realSubject;

    public MyInvocationHandler(RealSubject realSubject) {
        this.realSubject = realSubject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before method invocation.");
        Object result = method.invoke(realSubject, args);
        System.out.println("After method invocation.");
        return result;
    }
}